Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.

In [1]:
should_we_augment_data = True 
should_we_resize_data = True 
should_we_normalize_data = True 
EPOCHS = 10
BATCH_SIZE = 128

Step 0: Load The Data

In [2]:
# Load pickled data
import pickle
import numpy as np
# TODO: Fill this in based on where you saved the training and testing data

training_file = 'train.p'
validation_file='valid.p'
testing_file = 'test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)

    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [3]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results

# TODO: Number of training examples
n_train = len(X_train)

# TODO: Number of validation examples
n_validation = len(X_valid)

# TODO: Number of testing examples.
n_test = len(X_test)

# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape

# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(np.concatenate((y_train,y_valid,y_test),axis=0)))


print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)


import cv2
import matplotlib.pyplot as plt
%matplotlib inline


def transformto_gray_test(index):
    

    f, axarr = plt.subplots(1,4,figsize=(20,20))
    axarr[0].imshow(X_train[index])
    axarr[0].set_title( "original")
    axarr[1].imshow((X_train[index,:,:,0] + X_train[index,:,:,1] + X_train[index,:,:,2])/3,cmap = 'gray')
    axarr[1].set_title( "(R+G+B)/3")
    axarr[2].imshow(X_train[index,:,:,0],cmap='gray')
    axarr[2].set_title( "Choose R channel only")
    axarr[3].imshow(cv2.cvtColor(X_train[index], cv2.COLOR_RGB2GRAY),cmap='gray')
    axarr[3].set_title( "Opencv convert")


def transform__test(index):
    

    f, axarr = plt.subplots(1,4,figsize=(20,20))
    axarr[0].imshow(X_train[index])
    axarr[0].set_title( "original")
    axarr[1].imshow((X_train[index,:,:,0] + X_train[index,:,:,1] + X_train[index,:,:,2])/3,cmap = 'gray')
    axarr[1].set_title( "(R+G+B)/3")
    axarr[2].imshow(X_train[index,:,:,0],cmap='gray')
    axarr[2].set_title( "Choose R channel only")
    axarr[3].imshow(cv2.cvtColor(X_train[index], cv2.COLOR_RGB2GRAY),cmap='gray')
    axarr[3].set_title( "Opencv convert")

    
    
#transformto_gray_test(10000)  
#transformto_gray_test(20000)  
Number of training examples = 34799
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43
In [4]:
import numpy as np

def rotate(data,angle):
    M = cv2.getRotationMatrix2D((32/2,32/2),angle,1)
    dst = cv2.warpAffine(data,M,(32,32))
    return dst




def rotate_all_display(data):
        
    numbers = 8
    f, axarr = plt.subplots(1,numbers-1,figsize=(20,20))
    for angel in range(0,numbers-1):
        axarr[angel].imshow(rotate(data,(angel+1) * 360/8))
        axarr[angel].set_title(str((angel +1)*360/8))

def perspective_transform(data):
        
    pts1 = np.float32([[8,8],[24,8],[8,24],[24,24]])
    pts2 = np.float32([[0,0],[32,0],[0,32],[32,32]])
    M = cv2.getPerspectiveTransform(pts1,pts2)
    return cv2.warpPerspective(data,M,(32,32))


def affine_transform(data):
    pts1 = np.float32([[8,8],[16,8],[8,16]])
    pts2 = np.float32([[2,4],[12,2],[12,20]])
    M = cv2.getAffineTransform(pts1,pts2)
    return cv2.warpAffine(data,M,(32,32))

def rotate_all(data):
    all_data = []
    numbers = 8
    for angel in range(0,numbers-1):
        all_data.append(rotate(data,(angel+1) * 45))
    return all_data

def add_noise_to_image(img):

    h,w,c = img.shape # (768, 1024, 3)
    
    combined = []
    noise = np.random.randint(0,10,(h, w)) # design jitter/noise here
    zitter1 = np.zeros_like(img)
    zitter2 = np.zeros_like(img)
    zitter3 = np.zeros_like(img)

    zitter1[:,:,0] = noise  
    zitter2[:,:,1] = noise  
    zitter3[:,:,2] = noise  


    noise_added1 = cv2.add(img, zitter1)
    noise_added2 = cv2.add(img, zitter2)
    noise_added3 = cv2.add(img, zitter3)

    combined.append(noise_added1)
    combined.append(noise_added2)
    combined.append(noise_added3)

# shift each channel by 10 pixels
# R = img[:,:,0]
# G = img[:,:,1]
# B = img[:,:,2]
# RGBshifted = np.dstack( (
#     np.roll(R, 10, axis=0), 
#     np.roll(G, 10, axis=1), 
#     np.roll(B, -10, axis=0)
#     ))
# imshow(RGBshifted)
    
    
    return combined



def augment_data(data):
    
    rot_data = rotate_all(data)
    aff_data = affine_transform(data)
    per_data = perspective_transform(data)
    rot_data.append(aff_data)
    rot_data.append(per_data)

    noise_data = add_noise_to_image(data)
    rot_data.extend(noise_data)
    return rot_data



new_data = augment_data(np.array(X_train[10000]))
print(len(new_data))

f, axarr = plt.subplots(1,12,figsize=(20,20))
for i, data in zip(range(0,12),new_data):
    axarr[i].imshow(data)

    
12

Include an exploratory visualization of the dataset

In [5]:
# use matplotlib to display train/valid/test dataset distribution
import numpy as np

unique_train, counts_train = np.unique(y_train, return_counts=True)
unique_valid, counts_valid = np.unique(y_valid, return_counts=True)
unique_test, counts_test = np.unique(y_test, return_counts=True)

plt.figure(figsize=(10, 5))
plt.bar(unique_train, counts_train, alpha = .5, color = 'g')
plt.bar(unique_valid, counts_valid, alpha = .5, color = 'b')
plt.bar(unique_test, counts_test, alpha = .5, color = 'r')
plt.xlabel("SignNum", fontsize=16)
plt.ylabel("Count", fontsize=16)

# use pandas to display all data distribution
import pandas as pd

df = pd.DataFrame(np.concatenate((y_train,y_valid,y_test)),columns=['signnum'])
data = df.signnum.value_counts()

plt.figure(figsize=(10, 5))
ax = data.plot(kind='bar', title ="data distribution bar", legend=True, fontsize=12)

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?

In [6]:
assert(len(X_train) == len(y_train))
assert(len(X_valid) == len(y_valid))
assert(len(X_test) == len(y_test))

print(len(np.unique(np.concatenate((y_train,y_valid,y_test),axis=0))))


print()
print("Image Shape: {}".format(X_train[0].shape))
print("Training set Shape: {}".format(X_train.shape))

print()

print("Training Set:   {} samples".format(len(X_train)))
print("Validation Set: {} samples".format(len(X_valid)))
print("Test Set:       {} samples".format(len(X_test)))

def shuffle_data(X,y,test_size=0.20):
    from sklearn.model_selection import train_test_split
    return train_test_split(X, y, test_size=test_size, random_state=42)


is_test_validate_data_shuffled = False


if not is_test_validate_data_shuffled:
    X_tv_combined=np.concatenate((X_train,X_valid),axis=0)
    y_tv_combined=np.concatenate((y_train,y_valid),axis=0)
    assert(len(X_tv_combined) == (len(X_train)+len(X_valid)))
    assert(len(y_tv_combined) == (len(y_train)+len(y_valid)))    
    X_train, X_valid, y_train, y_valid=shuffle_data(X_tv_combined,y_tv_combined)
    is_test_validate_data_shuffled = True
    
assert is_test_validate_data_shuffled,'You skipped the step to shuffle the test and validate data'
43

Image Shape: (32, 32, 3)
Training set Shape: (34799, 32, 32, 3)

Training Set:   34799 samples
Validation Set: 4410 samples
Test Set:       12630 samples
In [7]:
#augument the training data
df = pd.DataFrame(y_train,columns=['signnum'])
data = df.signnum.value_counts()

max_value = max(data.values)
X_train_add = []
y_train_add = []

NEW_IMAGE_EACH_AUGMENT = 12

for i in data.index:
    target_increase = max_value - data[i]
    if(target_increase) > 0:
        indexs = ((df[df['signnum'].isin([i])]).index)
        increase = 0
        for index in indexs:
            test = augment_data(X_train[index])
#            print("augment data is {}".format(len(test)))
            X_train_add = X_train_add + test
            y_train_add.extend([i for j in range(NEW_IMAGE_EACH_AUGMENT)])
            increase = increase + NEW_IMAGE_EACH_AUGMENT
            if increase > target_increase:
                break
            
#            print("for signum:{}, with index:{},add:{} X, and {} y".format(i,index,len(X_train_add),len(y_train_add)))


print(X_train.shape)
X_train_add = np.array(X_train_add)
X_train_new  = np.concatenate((X_train,X_train_add))

y_train_add = np.array(y_train_add)
y_train_new  = np.concatenate((y_train,y_train_add))



df = pd.DataFrame(y_train,columns=['signnum'])
data = df.signnum.value_counts()

plt.figure(figsize=(10, 5))
ax = data.plot(kind='bar', title ="origianl data distribution bar", legend=True, fontsize=12)


df = pd.DataFrame(y_train_new,columns=['signnum'])
data = df.signnum.value_counts()

plt.figure(figsize=(10, 5))
ax = data.plot(kind='bar', title ="augmented data distribution bar", legend=True, fontsize=12)



TRAFFIC_SIGN_TYPE_NUMS =43

if should_we_augment_data:
    y_train = y_train_new
    X_train = X_train_new
(31367, 32, 32, 3)

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.

Other pre-processing steps are optional. You can try different techniques to see if it improves performance.

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [8]:
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.

import random
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

import pandas as pd
signnames_dict = pd.read_csv('signnames.csv')
signnames_mapping=signnames_dict.set_index("ClassId")


def resize(image_data, size):
    resize_image_data = []
    for img in image_data:
        resize_image = cv2.resize(img, size)
        resize_image_data.append(resize_image)

    return np.asarray(resize_image_data)  
    
def grayscale(image_data):
    return nil
  


def grayscale_resize(image_data):
    """Applies the Grayscale transform
    This will return an image with only one color channel
    but NOTE: to see the returned image as grayscale
    (assuming your grayscaled image is called 'gray')
    you should call plt.imshow(gray, cmap='gray')"""
    
    gray_data=[]
    
    # Or use BGR2GRAY if you read an image with cv2.imread()
    # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    for img in image_data:
        resize_image = cv2.resize(img, (32, 32))
        gray_image = cv2.cvtColor(resize_image, cv2.COLOR_RGB2GRAY)
        gray_data.append(np.reshape(gray_image,(32,32,1)))

    return np.asarray(gray_data)

    
def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])



def normalize(image_data):

    return (image_data-128.0)/128.0


if should_we_resize_data:
    X_train = resize(X_train,(32,32))
    X_valid = resize(X_valid,(32,32))
    X_test =  resize(X_test,(32,32))

if should_we_normalize_data:
    X_train = normalize(X_train)
    X_valid = normalize(X_valid)
    X_test = normalize(X_test)



#X_train[:,:,:,0] = test

#print(test.shape)
#X_test = np.reshape(test,(X_train.shape[0],X_train.shape[1],X_train.shape[2],1))
#print(X_test.shape)


#X_train= normalize_grayscale(X_train)
#X_valid= normalize_grayscale(X_valid)
#print(X_valid.shape)
#X_test= normalize_grayscale(X_test)
#print(X_test.shape)

Model Architecture

In [38]:
### Define your architecture here.
### Feel free to use as many code cells as needed.



from tensorflow.contrib.layers import flatten


# input 32X32X3, output 43, rewrite this part so those could be set as parameter

def MyNet(x,keep_prob):    
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1
    
    # SOLUTION: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x6.
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 60), mean = mu, stddev = sigma))
    conv1_b = tf.Variable(tf.zeros(60))
    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b

    # SOLUTION: Activation.
    conv1 = tf.nn.relu(conv1)

    # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 60, 180), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros(180))
    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
    
    # SOLUTION: Activation.
    conv2 = tf.nn.relu(conv2)

    # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # SOLUTION: Flatten. Input = 5x5x16. Output = 400.
    fc0   = flatten(conv2)
    
    
    drop_out = tf.nn.dropout(fc0, keep_prob)  # DROP-OUT here
    
    # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
    fc1_W = tf.Variable(tf.truncated_normal(shape=(4500, 1500), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(1500))
    fc1   = tf.matmul(drop_out, fc1_W) + fc1_b
    
    # SOLUTION: Activation.
    fc1    = tf.nn.relu(fc1)

    # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
    fc2_W  = tf.Variable(tf.truncated_normal(shape=(1500, 200), mean = mu, stddev = sigma))
    fc2_b  = tf.Variable(tf.zeros(200))
    fc2    = tf.matmul(fc1, fc2_W) + fc2_b
    
    # SOLUTION: Activation.
    fc2    = tf.nn.relu(fc2)

    # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 10.
    fc3_W  = tf.Variable(tf.truncated_normal(shape=(200, 43), mean = mu, stddev = sigma))
    fc3_b  = tf.Variable(tf.zeros(43))
    logits = tf.matmul(fc2, fc3_W) + fc3_b
    
    return logits
In [39]:
from sklearn.utils import shuffle

print(X_train.shape)
print(y_train.shape)

X_train, y_train = shuffle(X_train, y_train)
import tensorflow as tf




x = tf.placeholder(tf.float32, (None, 32, 32, 3))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, 43)
keep_prob = tf.placeholder(tf.float32)
(77567, 32, 32, 3)
(77567,)

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [40]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.

rate = 0.001

logits = MyNet(x,keep_prob)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
In [41]:
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y,keep_prob : 0.5})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples
In [42]:
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        X_train, y_train = shuffle(X_train, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y,keep_prob: 0.5})
            
        validation_accuracy = evaluate(X_valid, y_valid)
        print("EPOCH {} ...".format(i+1))
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()
        
    saver.save(sess, './lenet')

    print("Model saved")
Training...

EPOCH 1 ...
Validation Accuracy = 0.864

EPOCH 2 ...
Validation Accuracy = 0.909

EPOCH 3 ...
Validation Accuracy = 0.943

EPOCH 4 ...
Validation Accuracy = 0.958

EPOCH 5 ...
Validation Accuracy = 0.960

EPOCH 6 ...
Validation Accuracy = 0.957

EPOCH 7 ...
Validation Accuracy = 0.971

EPOCH 8 ...
Validation Accuracy = 0.950

EPOCH 9 ...
Validation Accuracy = 0.974

EPOCH 10 ...
Validation Accuracy = 0.973

Model saved
In [45]:
from sklearn.metrics import precision_recall_fscore_support as score



with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    test_accuracy = evaluate(X_test, y_test)
    print("Test Accuracy = {:.3f}".format(test_accuracy))
    
    classification = sess.run(tf.argmax(logits, 1), feed_dict={x: X_test,keep_prob : 0.5})
    precision, recall, fscore, support = score(y_test, classification)

    print('precision: {}'.format(precision))
    print('recall: {}'.format(recall))
    print('fscore: {}'.format(fscore))
    print('support: {}'.format(support))

    
    
Test Accuracy = 0.901
precision: [ 0.56097561  0.95147059  0.98237885  0.89073634  0.86619718  0.81041968
  0.97368421  0.84937238  0.87799564  0.96390658  0.98427673  0.97186701
  0.99185668  0.98710602  0.98529412  0.86864407  0.93670886  0.99122807
  0.94550409  0.58208955  0.80851064  0.70731707  0.95049505  0.70833333
  0.71559633  0.87984496  0.80295567  0.44444444  0.76404494  0.88235294
  0.9009009   0.74474474  0.96610169  0.90707965  0.87022901  0.95103093
  0.94059406  0.7012987   0.99223602  0.67924528  0.68644068  0.73239437
  0.8       ]
recall: [ 0.76666667  0.89861111  0.892       0.83333333  0.93181818  0.88888889
  0.74        0.90222222  0.89555556  0.94583333  0.94848485  0.9047619
  0.8826087   0.95694444  0.99259259  0.97619048  0.98666667  0.94166667
  0.88974359  0.65        0.84444444  0.64444444  0.8         0.68
  0.86666667  0.94583333  0.90555556  0.66666667  0.90666667  0.83333333
  0.66666667  0.91851852  0.95        0.97619048  0.95        0.94615385
  0.79166667  0.9         0.92608696  0.8         0.9         0.86666667
  0.84444444]
fscore: [ 0.64788732  0.92428571  0.93501048  0.86107922  0.89781022  0.84784254
  0.84090909  0.875       0.88668867  0.95478444  0.96604938  0.93711467
  0.93404908  0.97179126  0.98892989  0.91928251  0.96103896  0.96581197
  0.91677675  0.61417323  0.82608696  0.6744186   0.86877828  0.69387755
  0.7839196   0.91164659  0.85117493  0.53333333  0.82926829  0.85714286
  0.76628352  0.8225539   0.95798319  0.94036697  0.90836653  0.94858612
  0.85972851  0.78832117  0.95802099  0.73469388  0.77884615  0.79389313
  0.82162162]
support: [ 60 720 750 450 660 630 150 450 450 480 660 420 690 720 270 210 150 360
 390  60  90  90 120 150  90 480 180  60 150  90 150 270  60 210 120 390
 120  60 690  90  90  60  90]
In [46]:
df = pd.DataFrame({'precision':precision, 
                  'recall':recall,
                  'fscore':fscore,
                  'support':support})
df

# plt.figure(figsize=(10, 5))
# plt.bar(range(0,43), precision, alpha = .5, color = 'g')
# plt.bar(range(0,43), recall, alpha = .5, color = 'b')
# plt.bar(range(0,43), fscore, alpha = .5, color = 'r')
# plt.xlabel("SignNum", fontsize=16)
# plt.ylabel("Count", fontsize=16)
Out[46]:
fscore precision recall support
0 0.647887 0.560976 0.766667 60
1 0.924286 0.951471 0.898611 720
2 0.935010 0.982379 0.892000 750
3 0.861079 0.890736 0.833333 450
4 0.897810 0.866197 0.931818 660
5 0.847843 0.810420 0.888889 630
6 0.840909 0.973684 0.740000 150
7 0.875000 0.849372 0.902222 450
8 0.886689 0.877996 0.895556 450
9 0.954784 0.963907 0.945833 480
10 0.966049 0.984277 0.948485 660
11 0.937115 0.971867 0.904762 420
12 0.934049 0.991857 0.882609 690
13 0.971791 0.987106 0.956944 720
14 0.988930 0.985294 0.992593 270
15 0.919283 0.868644 0.976190 210
16 0.961039 0.936709 0.986667 150
17 0.965812 0.991228 0.941667 360
18 0.916777 0.945504 0.889744 390
19 0.614173 0.582090 0.650000 60
20 0.826087 0.808511 0.844444 90
21 0.674419 0.707317 0.644444 90
22 0.868778 0.950495 0.800000 120
23 0.693878 0.708333 0.680000 150
24 0.783920 0.715596 0.866667 90
25 0.911647 0.879845 0.945833 480
26 0.851175 0.802956 0.905556 180
27 0.533333 0.444444 0.666667 60
28 0.829268 0.764045 0.906667 150
29 0.857143 0.882353 0.833333 90
30 0.766284 0.900901 0.666667 150
31 0.822554 0.744745 0.918519 270
32 0.957983 0.966102 0.950000 60
33 0.940367 0.907080 0.976190 210
34 0.908367 0.870229 0.950000 120
35 0.948586 0.951031 0.946154 390
36 0.859729 0.940594 0.791667 120
37 0.788321 0.701299 0.900000 60
38 0.958021 0.992236 0.926087 690
39 0.734694 0.679245 0.800000 90
40 0.778846 0.686441 0.900000 90
41 0.793893 0.732394 0.866667 60
42 0.821622 0.800000 0.844444 90
In [47]:
ind = np.arange(43)
width = 0.3
plt.figure(figsize=(20, 10))
plt.bar(ind, precision, width,alpha = .5, color = 'g',label='precision')
plt.bar(ind+width, recall, width,alpha = .5, color = 'b',label='recall')
plt.bar(ind+width*2, fscore, width,alpha = .5, color = 'r',label='fscore')
plt.xlabel("SignNum", fontsize=16,)
plt.ylabel("Value", fontsize=16)
plt.legend()
Out[47]:
<matplotlib.legend.Legend at 0x114f5fb38>
In [ ]:
 

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

In [48]:
def show_all_sign():
    
    for i in range(0,43):
        indexs  = random.choice(np.where(y_train ==i))
        index = indexs[0]
        plt.figure(figsize=(11,8))
        plt.imshow(np.reshape(X_train[index],(32,32)),cmap='gray')
        plt.title(signnames_dict.iloc[i]['SignName'] + "number:"+str(i))
        plt.savefig('original/'+str(i)+'.png')   # save the figure to file
        plt.close()

Load and Output the Images

In [49]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
%matplotlib inline


import os

def load_images_from_folder_resize(folder):
    images = []
    for filename in os.listdir(folder):
        img = plt.imread(os.path.join(folder,filename))
        if img is not None:
            images.append(img)
    return images

def show_all_sign():
    images = []
    for filename in os.listdir(folder):
        img = plt.imread(os.path.join(folder,filename))
        if img is not None:
            images.append(img)
    return images


value=[0,40,1,1,1,36,3,17,14,8,13,14,2]
labels=np.asarray(value) 

images = load_images_from_folder_resize('web')

sample_size = len(images)

def show_image(images):

    f, axarr[0] = plt.subplots(1,5,figsize=(20,20))
    f, axarr[1]=  plt.subplots(1,5,figsize=(20,20))
    f, axarr[2] = plt.subplots(1,3,figsize=(20,20))

    for image,index in zip(images,range(0,len(images))):
        i1,i2 = divmod(index,5)
        axarr[i1][i2].imshow(add_noise_to_image(image)[2])

def add_noise_to_image(img):

    h,w,c = img.shape # (768, 1024, 3)
    
    combined = []
    noise = np.random.randint(0,200,(h, w)) # design jitter/noise here
    zitter1 = np.zeros_like(img)
    zitter2 = np.zeros_like(img)
    zitter3 = np.zeros_like(img)

    zitter1[:,:,0] = noise  
    zitter2[:,:,1] = noise  
    zitter3[:,:,2] = noise  


    noise_added1 = cv2.add(img, zitter1)
    noise_added2 = cv2.add(img, zitter2)
    noise_added3 = cv2.add(img, zitter3)

    combined.append(noise_added1)
    combined.append(noise_added2)
    combined.append(noise_added3)

    return combined


show_image(images)

image_test = resize(images,(32,32))

if should_we_normalize_data:
    image_test = normalize(image_test)

 

Predict the Sign Type for Each Image

In [50]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
import  tensorflow as tf


softmax = tf.nn.softmax(logits)

with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))
    
    test_accuracy = evaluate(image_test, labels)
    print("Test Accuracy = {:.3f}".format(test_accuracy))
    sess = tf.get_default_session()

#    top_5_classification = sess.run(tf.nn.top_k(logits, k=5), feed_dict={x:image_test})
    top_5_classification = sess.run(tf.nn.top_k(softmax, k=5), feed_dict={x:image_test,keep_prob : 0.5})

    print(top_5_classification)
    indices = top_5_classification.indices
    values  = top_5_classification.values
    
    f, axarr[0] = plt.subplots(1,5,figsize=(20,20))
    f, axarr[1]=  plt.subplots(1,5,figsize=(20,20))
    f, axarr[2] = plt.subplots(1,3,figsize=(20,20))

    for value, indice,image,index in zip(values,indices,images,range(0,len(images))):
        #plt.figure()
        #plt.imshow(image)
        C1 = signnames_dict.iloc[indice[0]]['SignName'] + "(" +str(value[0])+ " )"
        C2 = signnames_dict.iloc[indice[1]]['SignName']+ "(" +str(value[1])+ " )"
        C3 = signnames_dict.iloc[indice[2]]['SignName']+ "(" +str(value[2])+ " )"
        C4 = signnames_dict.iloc[indice[3]]['SignName']+ "(" +str(value[3])+ " )"
        C5 = signnames_dict.iloc[indice[4]]['SignName']+ "(" +str(value[4])+ " )"


        i1,i2 = divmod(index,5)

        axarr[i1][i2].imshow(image)
        axarr[i1][i2].set_title( C1 +"\n" + C2+"\n" +C3 +"\n" + C4 +"\n" + C5)
Test Accuracy = 0.231
TopKV2(values=array([[  1.00000000e+00,   1.26010783e-15,   3.01395128e-16,
          2.38738963e-16,   1.33518465e-16],
       [  9.99990106e-01,   6.08352002e-06,   3.42475164e-06,
          3.42849177e-07,   2.85708044e-08],
       [  9.99993205e-01,   6.15936551e-06,   5.42836574e-07,
          4.92784424e-10,   1.15357925e-10],
       [  6.42776012e-01,   3.56763870e-01,   3.92116403e-04,
          4.22754529e-05,   2.48620108e-05],
       [  9.99998212e-01,   1.52114171e-06,   1.64600706e-07,
          7.27040685e-08,   6.10434481e-10],
       [  4.63952065e-01,   2.37444252e-01,   1.82548389e-01,
          9.06325355e-02,   1.33032091e-02],
       [  9.99964714e-01,   3.27529924e-05,   1.82751228e-06,
          3.19441170e-07,   2.18187580e-07],
       [  9.99999762e-01,   2.22385040e-07,   2.91618465e-11,
          1.48297184e-12,   7.26426840e-14],
       [  6.90811098e-01,   3.08368474e-01,   5.07087098e-04,
          2.05837816e-04,   7.33580455e-05],
       [  1.00000000e+00,   7.51361817e-09,   2.16394350e-12,
          3.42865900e-13,   1.74645353e-14],
       [  9.53788579e-01,   4.61970158e-02,   1.25817432e-05,
          1.74023000e-06,   1.18018431e-08],
       [  9.98138666e-01,   1.86126202e-03,   3.75736565e-14,
          1.39392684e-23,   2.48415169e-27],
       [  9.82150257e-01,   7.47710094e-03,   5.04662422e-03,
          2.43125414e-03,   1.87675073e-03]], dtype=float32), indices=array([[ 0, 25,  5, 31,  3],
       [40, 38, 33, 35,  6],
       [ 1,  5,  3, 20,  6],
       [ 0,  1,  4, 21,  5],
       [19, 21, 18, 23, 31],
       [38, 36, 37, 39, 34],
       [24,  0, 18, 27, 28],
       [14, 17, 12, 29, 30],
       [14, 17,  1, 29, 24],
       [ 0, 21,  8,  4, 40],
       [26, 12, 23, 29, 21],
       [17, 12, 14, 11, 30],
       [ 5, 14,  3,  0,  2]], dtype=int32))

Analyze Performance

In [ ]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
#See above

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [ ]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.
#See above

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.


Step 4 (Optional): Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [ ]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(15,15))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
In [ ]: